<template>
  <view v-on:scroll.passive="onScroll">
    <transition name="fade">
      <view class="option-bar" v-show="scrollCtls.scrolledUp">
        <view
          class="float-icon upload-pic"
          @click="uploadPicClicked"
          v-show="!isUploading"
        ></view>
        <view
          class="float-icon modify-info"
          v-show="!isUploading"
          @click="gotoAlbumModify"
          :data-albumid="albumid"
        ></view>
        <view
          class="float-icon refresh-page"
          v-show="!isUploading"
          @click="requestPicIds"
        ></view>
        <!-- <view
          class="float-icon download-pic"
          v-show="!isUploading"
          @click="downloadPictureClicked"
        ></view> -->
      </view>
    </transition>
    <view>
      <view class="redundant-space"></view>
      <view class="waterfall-container" v-if="!isUploading">
        <view
          v-for="(item, index) in pic_list"
          :key="(item, index)"
          :data-picdetail="item"
          @click="gotoPictureDetail"
          class="waterfall-item"
        >
          <image :src="item.pic_display" mode="widthFix"></image>
          <view class="pic-desc">
            <view class="pic-id">{{ item.pic_id }}</view>
            <view>{{ item.pic_createTime }}</view>
          </view>
        </view>
      </view>
      <view v-else>
        <form enctype="multipart/form-data" @submit="submitFormUpload">
          <view>已选择</view>
          <image :src="chosenImgRes.tempFilePaths[0]" mode="widthFix"></image>
          <input name="pic_blob" :value="chosenImgRes.tempFilePaths[0]" />
          <view class="option-bar" v-show="scrollCtls.scrolledUp"
            ><button
              class="float-icon submit-upload"
              v-show="isUploading"
              form-type="submit"
            ></button>
            <view
              class="float-icon cancel-upload"
              v-show="isUploading"
              @click="cancelUploadingClicked"
            ></view
          ></view>
        </form>
      </view>
      <view class="redundant-space"></view>
      <view
        style="text-align: center; color: lightgrey"
        v-show="pic_list.length === 0"
        >点击加号上传图片</view
      >
    </view>
  </view>
</template>

<script>
import { mapState } from "vuex";
export default {
  data() {
    return {
      scrollCtls: { scrolledUp: true, startY: 0 },
      albumid: "",
      phone: "",
      pic_list: [
        // {
        //   pic_id: "xxxxxxxx",
        //   pic_createTime: "123456",
        //   pic_display: "/static/temp_pics/pic1.jpeg",
        //   phone: "xxxxxxxxxx",
        // },
        // {
        //   pic_id: "xxxxxxxx",
        //   pic_createTime: "123456",
        //   pic_display: "/static/temp_pics/pic2.jpeg",
        //   phone: "aaaaaaaaaaa",
        // },
        // {
        //   pic_id: "xxxxxxxx",
        //   pic_createTime: "123456",
        //   pic_display: "/static/temp_pics/pic3.png",
        //   phone: "bbbbbbbbbb",
        // },
        // {
        //   pic_id: "xxxxxxxx",
        //   pic_createTime: "123456",
        //   pic_display: "/static/temp_pics/pic4.png",
        //   phone: "ccccccccccccccc",
        // },
      ],
      isUploading: false,
      chosenImgRes: null,
    };
  },
  computed: mapState(["localData", "hasLogin"]),
  onLoad: function (e) {
    e = JSON.parse(e.albumid);
    // console.log(e);
    this.albumid = e.id;
    this.phone = e.phone;
    uni.setNavigationBarTitle({ title: "相册 - " + e.id });
    // TODO: 发送请求，获取相册中的图片
    // 是否考虑优先加载本地已经有的
    this.requestPicIds();
  },
  mounted() {
    window.addEventListener("scroll", this.onscroll);
    uni.$on("poppic", this.popDeletedPic);
  },
  methods: {
    onscroll: function () {
      if (scrollY < this.scrollCtls.startY) {
        this.scrollCtls.scrolledUp = true;
      } else if (scrollY > this.scrollCtls.startY) {
        this.scrollCtls.scrolledUp = false;
      }
      this.scrollCtls.startY = scrollY;
    },
    uploadPicClicked: function () {
      if (!this.localData.loggedin) {
        uni.navigateTo("/pages/login/login");
        return;
      }
      console.log("upload clicked");
      uni.chooseImage({
        success: (chooseImgRes) => {
          this.isUploading = true;
          this.chosenImgRes = chooseImgRes;
          console.log(chooseImgRes);
        },
      });
    },
    submitUploadTry2: function (e) {
      let values = e.detail.value;
      values.option = "upload";
      values.pic_album = this.albumid;
      values.pic_description = "random description";
      console.log("postValues", values);
      let postData = {
        option: "upload",
        pic_album: this.albumid,
        pic_description: "random",
        pic_blob: values.pic_blob,
        "Content-Type": "multipart/form-data; boundary=Multipart Boundary",
      };
      uni.uploadFile({
        url: "http://192.168.43.117:8080" + this.urlApi.pic,
        data: postData,
        name: "file",
        filePath: values.pic_blob,
        header: {
          "Content-Type": "multipart/form-data; boundary=Multipart Boundary",
        },
        success: (res) => {
          console.log(res);
        },
        fail: (err) => {
          console.log(err);
        },
      });
    },
    submitFormUpload: function (e) {
      let values = e.detail.value;
      values.option = "upload";
      values.pic_album = this.albumid;
      values.pic_description = "random description";
      console.log("postValues", values);
      let postData = {
        option: "upload",
        pic_album: this.albumid,
        pic_description: "random",
        pic_blob: values.pic_blob,
        "Content-Type": "multipart/form-data; boundary=Multipart Boundary",
        "Access-Control-Allow-Origin": "*",
      };
      // this.$http
      //   .post(this.urlApi.pic, postData, {
      //     header: {
      //       "Content-Type": "multipart/form-data; boundary=Multipart Boundary",
      //     },
      //   })
      this.$http
        .upload(this.urlApi.pic, {
          filePath: values.pic_blob,
          formData: postData,
          name: "file",
          header: {
            "Access-Control-Allow-Origin": "*",
            "content-type": "multipart/form-data",
            // "Content-Type": "application/x-www-form-urlencoded"
          },
        })
        .then((res) => {
          uni.hideLoading();
          let stauts = res.data.status;
          console.log(res);
          switch (stauts) {
            case "100": {
              uni.showToast({ title: "上传成功" });
              let pic_obj = {
                pic_id: res.data.pic_id,
                pic_createTime: res.data.pic_createtime,
                pic_display: values.pic_blob,
              };
              this.pic_list.push(pic_obj);
              this.isUploading = false;
              this.chosenImgRes = null;
              break;
            }
            case "101": {
              uni.showToast({ title: "上传失败", icon: "error" });
              break;
            }
            default: {
              console.log("err");
              break;
            }
          }
        })
        .catch((err) => {
          uni.hideLoading();
          console.log("err", err);
          uni.showToast({ title: "请求失败", icon: "error" });
        });
    },
    submitUploadClicked: function () {
      uni.showLoading({ title: "上传中" });
      const tempFile = this.chosenImgRes.tempFiles[0];
      // console.log(tempFile);
      let formData = new FormData();
      formData.append("option", "upload");
      formData.append("pic_album", this.albumid);
      formData.append("pic_description", "random description");
      formData.append("pic_blob", values.pic_blob);
      this.$http
        .upload(this.urlApi.pic, {
          files: this.chosenImgRes.tempFiles,
          fileType: "image",
          header: {
            "Content-Type": "multipart/form-data; boundary=Multipart Boundary",
          },
          formData: formData,
        })
        // this.$http
        //   .post(this.urlApi.pic, postData, {
        //     header: {
        //       "Content-Type":
        //         "multipart/form-data;boundary=----WebKitFormBoundary98099456765456651232245644567855643876789898",
        //     },
        //   })
        .then((res) => {
          uni.hideLoading();
          let stauts = res.data.status;
          console.log(res);
          switch (stauts) {
            case "100": {
              uni.showToast({ title: "上传成功" });
              let pic_obj = {
                pic_id: res.data.pic_id,
                pic_createTime: res.data.pic_createtime,
                pic_display: tempFile,
              };
              this.pic_list.push(pic_obj);
              this.isUploading = false;
              this.chosenImgRes = null;
              break;
            }
            case "101": {
              uni.showToast({ title: "上传失败", icon: "error" });
              break;
            }
          }
        })
        .catch((err) => {
          uni.hideLoading();
          console.log(err);
          uni.showToast({ title: "请求失败", icon: "error" });
        });
    },
    cancelUploadingClicked: function () {
      this.isUploading = false;
      this.chosenImgRes = null;
    },
    gotoPictureDetail: function (e) {
      // console.log("album", e.currentTarget.dataset.picdetail);
      uni.navigateTo({
        url:
          "/pages/details/picDetail" +
          "?picid=" +
          encodeURIComponent(JSON.stringify(e.currentTarget.dataset.picdetail)),
      });
    },
    requestPicIds: function () {
      // 首先请求图片的 id
      let postData = {
        option: "getPictureID",
        pic_album: this.albumid,
      };
      // console.log("preloadPictures", postData);
      this.$http
        .post(this.urlApi.pic, postData)
        .then((res) => {
          let status = res.data.status;
          // console.log(res.data);
          switch (status) {
            case "100": {
              uni.showToast({ title: "获取成功" });
              let pic_ids = res.data.pic_id;
              console.log(pic_ids);
              this.getPicInfoOnByOne(pic_ids);
              break;
            }
            case "101": {
              uni.showToast({ title: "获取失败", icon: "error" });
              break;
            }
          }
        })
        .catch((err) => {
          uni.showToast({ title: "请求失败", icon: "error" });
          console.log(err.data);
        });
    },
    getPicInfoOnByOne: function (pic_ids) {
      console.log("One by one", pic_ids);
      this.pic_list = [];
      for (var i = 0; i < pic_ids.length; i++) {
        let pid = pic_ids[i];
        let postData = {
          option: "download",
          pic_id: pid,
        };
        this.$http
          .download(this.urlApi.pic, { params: postData })
          .then((res) => {
            console.log(res);
            this.pic_list.push({
              pic_id: pid,
              pic_display: res.tempFilePath,
              phone: this.phone,
            });
          })
          .catch((err) => {
            console.log(err);
            uni.showToast({ title: pid + "获取失败", icon: "error" });
          });
      }
    },
    gotoAlbumModify: function (e) {
      uni.navigateTo({
        url: "/pages/details/albumModify" + "?albumid=" + this.albumid,
      });
    },
    downloadPictureClicked: function () {
      let postData = {
        option: "download",
        pic_id: "1234562021121114314920220103162347",
      };
      console.log("download", postData);
      this.$http
        .download(this.urlApi.pic, { params: postData })
        .then((res) => {
          console.log(res);
          // let bytes = new Uint8Array(res.data);
          // let blob = new Blob([bytes], { type: "image/png" });
          // let url = window.URL.createObjectURL(blob);
          let img = {
            pic_display: res.tempFilePath,
            pic_id: postData.pic_id,
            pic_createTime: "00",
          };
          console.log(img);
          this.pic_list.push(img);
        })
        .catch((err) => {
          console.log(err.data);
        });
    },
    popDeletedPic: function (e) {
      console.log(e);
      for (let i = 0; i < this.pic_list.length; i++) {
        if (e.pic_id == this.pic_list[i].pic_id) {
          this.pic_list.splice(i, 1);
        }
      }
    },
  },
};
</script>

<style>
.redundant-space {
  width: 100%;
  height: 10rpx;
}
.waterfall-container {
  padding: 20rpx;
  column-count: 2;
  column-gap: 20rpx;
}
.waterfall-item {
  break-inside: avoid;
  box-shadow: 0 0 10rpx lightgray;
  margin: 0 0 20rpx 0;
  cursor: pointer;
}
.option-bar {
  position: fixed;
  right: 10rpx;
  bottom: 10rpx;
  z-index: 1000;
}
.float-icon {
  font-family: codicon;
  background-color: #fff;
  /* width: 80rpx;
  height: 80rpx; 
  line-height: 80rpx;*/
  /* text-align: center; */
  padding: 20rpx;
  font-size: 42rpx;
  border-radius: 50%;
  box-shadow: 0 0 20rpx grey;
  cursor: pointer;
  margin: 20rpx;
}
uni-button {
  line-height: 42rpx;
  border: none;
}
.upload-pic::before {
  content: "\ea60";
}
.modify-info::before {
  content: "\eb94";
}
.cancel-upload::before {
  content: "\ea76";
}
.submit-upload::before {
  content: "\eab2";
}
.refresh-page::before {
  content: "\eb37";
}
.download-pic::before {
  content: "\eac2";
}
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s;
}
.fade-enter,
.fade-leave-to {
  opacity: 0;
}
uni-image {
  width: 100%;
}
.pic-desc {
  padding: 0 0.5em 0.5em 0.5em;
}
.pic-id {
  white-space: nowrap;
  overflow: hidden;
  font-size: 20rpx;
}
</style>